﻿using System.Windows;
using System.Collections.ObjectModel;
using STeaL.Collections.Generic;
using STeaL.Collections.ObjectModel;

namespace ObservableKeyedCollection {

  public partial class MainWindow : Window {

    public MainWindow() {
      InitializeComponent();
      adaptor_ = new multiset_adaptor<KeyAndValue>(data_.SortedWords, (x,y) => x.Key.CompareTo(y.Key) < 0 );
      DataContext = data_;
    }

    private BindData data_ = new BindData() { Words = new Dictionary(), SortedWords=new ObservableCollection<KeyAndValue>() };

    private void btnAdd_Click(object sender, RoutedEventArgs e) {
      KeyAndValue item = new KeyAndValue() { Key = txtKey.Text, Value = txtValue.Text };
      if (data_.Words.Contains(item.Key)) {
        txtValue.Text = "already exists.";
      } else {
        data_.Words.Add(item);
      }
      if ( !adaptor_.Contains(item) ) {
        adaptor_.Add(item);
      }
    }

    private void btnRemove_Click(object sender, RoutedEventArgs e) {
      KeyAndValue item = new KeyAndValue() { Key = txtKey.Text };
      if (!data_.Words.Remove(item.Key)) {
        txtValue.Text = "no such Key.";
      }
      adaptor_.Remove(item);
    }

    multiset_adaptor<KeyAndValue> adaptor_;
  }

  public class KeyAndValue {
    public string Key { get; set; }
    public string Value { get; set; }
  }

  public class Dictionary : ObservableKeyedCollection<string, KeyAndValue> {
    protected override string GetKeyForItem(KeyAndValue item) {
      return item.Key;
    }
  }

  public class BindData {
    public Dictionary Words { get; set; }
    public ObservableCollection<KeyAndValue> SortedWords { get; set; }
  }
}
